package org.akomantoso.core.io.util.group;

import java.io.IOException;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;

import org.akomantoso.core.data.Hcontainer;
import org.akomantoso.core.data.HierElements;
import org.akomantoso.core.io.Input;
import org.akomantoso.core.io.InputConstants;
import org.akomantoso.core.io.util.Instantiator;
import org.akomantoso.core.util.MapUtil;

/**
 * @author <a href="mailto:jacques.militello@gmail.com">Jacques Militello</a>
 */
public final class HierElementsGroup {

	private HierElementsGroup() {
	}

	public static final Map<String, Instantiator<HierElements>> MAP;
	
	static {
		Map<String, Instantiator<HierElements>> temp  = new IdentityHashMap<String, Instantiator<HierElements>>();
		MapUtil.copy(ANhierGroup.MAP,temp);
		temp.put(Hcontainer.ELEMENT.intern(), new Instantiator<HierElements>() {
			public Hcontainer instantiate() {
				return new Hcontainer();
			}
		});
		MAP = temp;
	}
	
	public static void read(Input in,List<HierElements> elements) throws IOException {
		HierElements element = null;
		final String localName = in.getLocalName();
		
		while(true) {
			in.readNext();
			switch (in.getEventType()) {
			case InputConstants.START_ELEMENT:
				elements.add(element = instantiate(in.getLocalName()));
				element.readExternal(in);
				break;			
			case InputConstants.END_ELEMENT:
				if (localName == in.getLocalName()) {
					return;
				} 
			}
		}
	}
	
	private static HierElements instantiate(String element) {
		final Instantiator<? extends HierElements> instatiator = MAP.get(element);
		if (instatiator == null) {
			throw new RuntimeException("Tag [" + element + "] not supported HierElement ?!?");
		}
		return instatiator.instantiate();
	}
}